<template>
  <el-dialog v-model="dialogVisible" :title="dialogFlag === 'create' ? '新建配置' : '编辑配置'" width="40%" @close="cancelFn">
    <el-tabs v-model="activeTabName" type="card" class="demo-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="业务" name="biz" :disabled="disabledTab === 'biz'">
        <el-form ref="bizFormRef" :model="bizForm" :rules="bizRules" class="demo-ruleForm" label-width="120px" status-icon
          style="width: 50%">
          <el-form-item label="业务名称" prop="bizName">
            <el-input v-model="bizForm.bizName" placeholder="请输入业务名称" />
          </el-form-item>
          <el-form-item label="业务编码" prop="bizCode">
            <el-input v-model="bizForm.bizCode" placeholder="请输入业务编码（为9位数字，末三位为000）" :disabled="dialogFlag === 'edit'" />
          </el-form-item>
          <el-form-item label="车端路径" prop="">
            <el-input v-model="bizForm.carPath" placeholder="请输入绝对路径" />
          </el-form-item>
        </el-form>

      </el-tab-pane>
      <el-tab-pane label="子业务" name="subBiz" :disabled="disabledTab === 'subBiz'">
        <el-form ref="subBizFormRef" :model="subBizForm" :rules="subBizRules" class="demo-ruleForm" label-width="120px"
          status-icon style="width: 50%">
          <el-form-item label="业务名称" prop="bizName">
            <el-select v-model="subBizForm.bizName" placeholder="请选择业务名称" style="width: 100%" :disabled="dialogFlag === 'edit'">
              <el-option v-for="item in bizOptions" :key="item.bizId" :label="item.bizName" :value="item.bizName" />
            </el-select>
          </el-form-item>
          <el-form-item label="子业务" prop="subBizName">
            <el-input v-model="subBizForm.subBizName" placeholder="请输入子业务名称" />
          </el-form-item>
          <el-form-item label="子业务编码" prop="">
            <el-input v-model="subBizForm.subBizCode" placeholder="请输入子业务编码（为9位数字，末三位非000）" :disabled="dialogFlag === 'edit'" />
          </el-form-item>
          <el-form-item label="车端路径" prop="">
            <el-input v-model="subBizForm.carPath" placeholder="请输入绝对路径" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelFn">取消</el-button>
        <el-button type="primary" @click="confirmFn">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script  setup>
import { reactive, ref, toRaw, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createApi, updateApi } from '@/api/fileBusinessConfigurationApi.js';
import { queryBizList } from '@/api/fileListApi.js';
// 弹窗开关
const dialogVisible = ref(false);
// 标识：创建、编辑
let dialogFlag = ref('create')
// 编辑选中的该条id
let editBusinessConfigurationId = null
// 当前选中的tab： 业务 、子业务
let activeTabName = ref('biz')
// 业务的form ref 
let bizFormRef = ref(null)
// 子业务的form ref 
let subBizFormRef = ref(null)
// 业务的form表单及规则
const bizForm = reactive({
  bizName: '',
  bizCode: '',
  carPath: ''
})
const bizRules = reactive({
  bizName: [{ required: true, message: '请输入业务名称', trigger: 'blur' }],
  bizCode: [{ required: true, message: '请输入业务编码', trigger: 'blur' }],
})
// 子业务的form表单及规则
const subBizForm = reactive({
  bizName: '',
  subBizName: '',
  subBizCode: '',
  carPath: ''
})
const subBizRules = reactive({
  bizName: [{ required: true, message: '请选择业务名称', trigger: 'change' }],
  subBizName: [{ required: true, message: '请输入子业务名称', trigger: 'blur' }],
})
// 存放业务名称的列表（创建子业务时选择的业务options）
const bizOptions = ref([])
// 编辑时被禁用的tab: 业务 、子业务
let disabledTab = ref('')

const emit = defineEmits(['feedbackFn']);

// 查询业务的下拉选项
const getBizList = () => {
  queryBizList().then((res) => {
    if (res.data.code === 200) {
      let response = res.data.data;
      bizOptions.value = response;
    }
  })
};
// 点击切换tab(业务、子业务)
const handleTabClick = (pane) => {
  activeTabName.value = pane.props.name
  if (activeTabName.value === 'subBiz') {
    getBizList()
  }
}
// 新建配置 、 编辑时打开弹窗的操作
const switchVisible = (flag, data) => {
  dialogVisible.value = true;
  dialogFlag.value = flag;
  disabledTab.value = '';
  activeTabName.value = 'biz'
    // 当点击创建打开弹窗时，将2个tab下的所有数据清空
  if(dialogFlag.value === 'create'){
    nextTick(() => {
      bizFormRef.value.resetFields()
      subBizFormRef.value.resetFields()
      bizForm.carPath = ''
      subBizForm.subBizCode = ''
      subBizForm.carPath = ''
    });
  }
  // 当点击编辑打开弹窗时，判断是业务数据或子业务数据，回显对应数据进form表单，并将另一个置为禁用
  if (dialogFlag.value === 'edit') {
    editBusinessConfigurationId = data.id
    // 业务
    if(data.bizFlag){
      // 当该条数据为业务数据时，子业务的弹窗不可点击
      // 默认在 业务tab下， 回显业务弹窗下的数据
      disabledTab.value = 'subBiz'
      activeTabName.value = 'biz'
      for (let k in data) {
        delete bizForm[k];
        bizForm[k] = data[k] || '';
      }
    }else {
      // 当该条数据为子业务数据时，业务的弹窗不可点击
      // 默认在 子业务tab下， 回显子业务弹窗下的数据
      disabledTab.value = 'biz'
      activeTabName.value = 'subBiz'
      for (let k in data) {
        delete subBizForm[k];
        subBizForm[k] = data[k] || '';
      }
    }

  }
}
// 弹窗里的提交，先去校验表单，通过后再执行submitFn 提交给后端
const confirmFn = () => {
  if (activeTabName.value === 'biz') {
    if (!bizFormRef) return
    bizFormRef.value.validate((valid) => {
      if (valid) {
        submitFn()
      } else {
        return false
      }
    })
  }
  if (activeTabName.value === 'subBiz') {
    if (!subBizFormRef) return
    subBizFormRef.value.validate((valid) => {
      if (valid) {
        submitFn()
      } else {
        return false
      }
    })
  }

}

// 提交： 分为 创建业务 、 创建子业务 、 编辑业务 、编辑子业务 4个情况
const submitFn = () => {
  // 创建
  if (dialogFlag.value === 'create') {
    let createBy = '';
    try {
      createBy = JSON.parse(localStorage.getItem('userInfo')).employeeId;
    } catch (e) {
    }
    // 创建业务
    let req = {}
    if (activeTabName.value === 'biz') {
      let rawBizForm = toRaw(bizForm)
      req = { ...rawBizForm, createBy, bizFlag: true }
    }
    // 创建子业务
    if (activeTabName.value === 'subBiz') {
      let rawSubBizForm = toRaw(subBizForm)
      req = { ...rawSubBizForm, createBy, bizFlag: false }
    }
    createApi(req).then((res) => {
      if (res.data.code === 200) {
        ElMessage({
          message: '新增成功',
          type: 'success',
        })
        cancelFn();
        emit('feedbackFn')
      }
    });
  }
  // 编辑
  if (dialogFlag.value === 'edit') {
    let updateBy = '';
    try {
      updateBy = JSON.parse(localStorage.getItem('userInfo')).employeeId;
    } catch (e) {
    }
        // 编辑业务
        let req = {}
    if (activeTabName.value === 'biz') {
      let rawBizForm = toRaw(bizForm)
      req = { ...rawBizForm, updateBy, id: editBusinessConfigurationId }
    }
    // 编辑子业务
    if (activeTabName.value === 'subBiz') {
      let rawSubBizForm = toRaw(subBizForm)
      req = { ...rawSubBizForm, updateBy, id: editBusinessConfigurationId }
    }
    delete req.createBy
    delete req.createTime
    updateApi(req).then((res) => {
      if (res.data.code === 200) {
        ElMessage({
          message: '更新成功',
          type: 'success',
        })
        dialogVisible.value = false;
        emit('feedbackFn')
      }
    });
  }
}
//取消 、关闭弹窗
const cancelFn = () => {
  dialogVisible.value = false
  // 表单初始化
  bizFormRef.value.resetFields()
  subBizFormRef.value.resetFields()
}

defineExpose({
  switchVisible
})

</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>